DECLARE @xml XML

SET @xml = 
(
    SELECT
        FragmentId           = ISNULL(FragmentId,0)
    ,   FragmentName         = ISNULL(FragmentName,'')
    ,   FragmentDisplayName  = CAST(ISNULL(FragmentDisplayName,'') AS xml)
    ,   SortOrdinal          = ISNULL(CAST(SortOrdinal AS varchar(16)),'')
    ,   CreateDate           = ISNULL(Core.dbo.fDateFormat(@GlobalDateFormat,CreateDate),'')
    ,   EndDate              = ISNULL(CAST(EndDate AS varchar(64)),'')
    ,   ModificationDate     = Core.dbo.fDateFormat(@GlobalDateFormat,GETDATE())
    ,   DocumentId           = ISNULL(CAST(DocumentId AS varchar(16)),'')
    ,   PrevFragmentId       = ISNULL(CAST(PrevFragmentId AS varchar(16)),'')
    ,   NextFragmentId       = ISNULL(CAST(NextFragmentId AS varchar(16)),'')
    ,   IsPrevious           = ISNULL(IsPrevious,0)
    ,   IsNext               = ISNULL(IsNext,0)
    ,   IsWrapper            = ISNULL(IsWrapper,0)
    ,   ClientId             = ISNULL(ClientId,'')
    ,   IsActive             = ISNULL(IsActive,0)
    FROM
        Fragment
    WHERE
        DocumentId IN
        (
            SELECT
                DocumentId
            FROM
                SegmentDocument
            WHERE
            (
                    SegmentDocument.SegmentId = @SegmentId
                OR
                    dbo.fSegmentIsChildOf(SegmentDocument.SegmentId, dbo.fGetSegmentName(@SegmentId)) = 1
            )
            AND
                SegmentDocument.DocumentId = Fragment.DocumentId
        )
    OR
        DocumentId IN
        (
            SELECT
                DocumentId
            FROM
                Document
            WHERE
            (
                    Document.SegmentId = @SegmentId
                OR
                    dbo.fSegmentIsChildOf(Document.SegmentId, dbo.fGetSegmentName(@SegmentId)) = 1
            )
            AND
                Document.DocumentId = Fragment.DocumentId
        )
    FOR XML AUTO, ELEMENTS, ROOT('ChildFragments')
)

SELECT @xml
